<!--
 * @Author: ChunLai
 * @Date: 2022-11-03 17:10:04
 * @LastEditTime: 2025-11-19 09:06:20
 * @Description: 客服投保版海报
 * @FilePath: \01.latest-short-insure\src\views\poster\components\ServicePoster.vue
-->
<template>
  <div class="wrapperp">
    <div class="content">
      <div class="bg">
        <div class="imgBoxs">
          <div>
            <van-swipe :aspect-ratio="1100 / 800" @change="onChange">
              <van-swipe-item
                class="swiper-demo-img"
                v-for="(item, index) in imgList"
                :key="index"
              >
                <img :src="item" />
              </van-swipe-item>
            </van-swipe>
          </div>
          <div class="ptxt-box-1">
            <div class="tip-box tip-box-ts">提示</div>
            <div class="tip-box-tt tip-box-tt-ts">
              投保前请仔细阅读保险条款、责任免除等
            </div>
            <div class="tip-box tip-box-xs">销售</div>
            <div class="tip-box-tt tip-box-tt-xs">民盛保险代理有限公司</div>
          </div>
          <div class="proInfo2">本产品由{{ gysFullName }}承保</div>
        </div>
        <div class="info2Boxs">
          <canvas id="QRCode"></canvas>
          <template v-if="canvasQRCodeUrl">
            <div class="imgEwmBottomRight">
              <img :src="canvasQRCodeUrl" alt="" />
            </div>
            <div class="ewm-tt">长按二维码了解详情</div>
          </template>
          <div class="name-phone">
            <span>{{ name }}</span>
            <span class="s-phone">{{ phone }}</span>
          </div>
          <div class="img-top-bg">
            <div class="user-img">
              <img
                :src="headImg || '//wxou.mschn.cn/app_h5/insurance/img/man.png'"
                alt=""
                @error="imageLoadError"
              />
            </div>
          </div>
          <div class="p-info">
            <div class="mt10">{{ companyName }}</div>
            <div class="mt6">
              执业证号：<span>{{ certificate }}</span>
            </div>
          </div>
        </div>
      </div>
      <div class="bottom">
        <div class="moments" @click="downLoad('1')">
          <img :src="`${imgUrlPath}/icons/moments.png`" />
        </div>
        <div class="weChat" @click="downLoad('2')">
          <img :src="`${imgUrlPath}/icons/weChat.png`" />
        </div>
      </div>
    </div>
    <canvas id="myCanvas"></canvas>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { saveFile } from "@/utils/index";
import { canvasDrawMixin } from "./mixin.js";
import QRCode from "qrcode";

export default {
  name: "ServicePoster",
  data() {
    return {
      vLoad: false,
      name: "",
      phone: "",
      headImg: "",
      slideIndex: 0,
      canvasQRCodeUrl: "",
      certificate: "",
      companyName: "",
      clerkWorkNum: "", // 出单员
      kfid: "", // 客服id
    };
  },
  computed: {
    ...mapGetters({
      imgList: "varietyInfo/posters",
      gysFullName: "dictionary/gysFullName",
      productName: "varietyInfo/productName",
      tgForInsureLink: "page/tgForInsureLink",
      tgNoneInsuAgent: "page/tgNoneInsuAgent",
    }),
  },
  mixins: [canvasDrawMixin],
  created() {
    const querys = this.$route.query;
    if (querys.kfid) {
      this.kfid = querys.kfid;
    }

    this.GetStaffInfo();
  },
  methods: {
    imageLoadError() {
      // console.log('Image failed to load');
      this.headImg = "//wxou.mschn.cn/app_h5/insurance/img/man.png";
    },
    onChange(index) {
      this.slideIndex = index;
    },
    // 获取业务员姓名、联系方式
    GetStaffInfo() {
      const query = this.$route.query;
      let worknum = this.workNum;
      // 出单员岗位号
      if (query.clerkWorkNum) {
        worknum = query.clerkWorkNum;
        this.clerkWorkNum = query.clerkWorkNum;
      }
      this.$store.dispatch("apis/getStaffDatas", worknum).then((res) => {
        this.$nextTick(() => {
          this.name = res.name;
          this.phone = res.phone;
          this.certificate = res.certificate;
          this.companyName = res.companyName;
          this.headImg =
            res.headImg && res.headImg.indexOf("http") === -1
              ? `/${res.headImg}`
              : `${res.headImg}`;
          // 直接使用投保链接
          // 李建伟--陈文客服二维码
          if (
            this.tgForInsureLink.length > 0 &&
            !this.tgNoneInsuAgent.includes(this.clerkWorkNum)
          ) {
            if (this.tgForInsureLink.includes(this.mainRiskCode)) {
              this.getCanvasQr();
              return;
            }
          }
          // 生成客服链接二维码
          this.getServiceLink();
        });
      });
    },
    getServiceLink() {
      this.vLoad = true;
      this.$http
        .post("/wechart/getKfUrl", {
          workNum: this.clerkWorkNum || "",
          scene: "insure",
        })
        .then((res) => {
          this.vLoad = false;
          if (res.url) {
            // 定义固定参数： 险种编码；业务员；推广员；productNo
            let prms = `${this.mainRiskCode};${this.workNum};${this.clerkWorkNum};`;
            if (this.proIdCode) {
              prms += `${this.proIdCode}`;
            }
            console.log("scene_param", prms);
            let insureUrl = `${res.url}&scene_param=${encodeURIComponent(
              prms
            )}`;
            this.getCanvasQr(insureUrl);
          }
        })
        .catch((err) => {
          this.vLoad = false;
        });
    },
    getCanvasQr(insureUrl = "") {
      let insuLink = `${window.location.origin}${window.location.pathname}?company=${this.gysEngName}&workNum=${this.clerkWorkNum}&mcode=${this.mainRiskCode}&tgWorkNum=${this.workNum}`;
      if (this.proIdCode) {
        insuLink += `&productCode=${this.proIdCode}`;
      }
      let that = this,
        QRCodeMsg = `${insuLink}&skind=insure`, //生成的二维码为URL地址js
        eleMsg = document.getElementById("QRCode"),
        canvasOpts = {
          errorCorrectionLevel: "L", //容错级别
          type: "image/png", //生成的二维码类型
          quality: 0.9, //二维码质量
          margin: 1, //二维码留白边距
          width: 150, //宽
          height: 150, //高
          text: "民盛保代", //二维码内容
          color: {
            dark: "#333333", //前景色
            light: "#fff", //背景色
          },
        };
      if (insureUrl) {
        QRCodeMsg = insureUrl;
      }
      console.log("getCanvasQr", QRCodeMsg);
      // 将获取到的数据（val）画到eleMsg（canvas）上
      QRCode.toCanvas(eleMsg, QRCodeMsg, canvasOpts, function (error) {
        console.log(error);
        let canvasQRCodeUrl = eleMsg.toDataURL("image/png");
        that.canvasQRCodeUrl = canvasQRCodeUrl;
      });
    },
    downLoad(type) {
      var that = this;
      var canvas = document.getElementById("myCanvas");
      var ctxc = canvas.getContext("2d");
      canvas.width = 750;
      canvas.height = 1286;
      //处理等比拉伸压缩用户图片并居中裁剪
      var newimg = new Image();
      newimg.setAttribute("crossOrigin", "Anonymous");
      newimg.src = this.imgList[that.slideIndex];

      newimg.onload = function () {
        ctxc.drawImage(newimg, 0, 0, 750, 1006);
        let tipTxt = `提示`;
        let c2widths = tipTxt.length * 24;
        that.fillRoundRect(
          ctxc,
          10,
          15,
          c2widths + 10,
          32,
          16,
          "rgba(255, 255, 255,0)",
          "rgba(51, 51, 51,0.7)"
        );
        ctxc.fillStyle = "#282828";
        ctxc.font = "bold 20px sans-serif";
        ctxc.fillText(tipTxt, 19, 37, 40);

        let xsTxt = `销售`;
        let c3widths = xsTxt.length * 24;
        that.fillRoundRect(
          ctxc,
          490,
          15,
          c3widths + 10,
          32,
          16,
          "rgba(255, 255, 255,0)",
          "rgba(51, 51, 51,0.7)"
        );
        ctxc.fillText(xsTxt, 500, 37, 40);

        let tipTxt2 = `投保前请仔细阅读保险条款、责任免除等`;
        ctxc.fillStyle = "#282828";
        ctxc.font = "bold 18px sans-serif";
        ctxc.fillText(tipTxt2, 82, 36);

        let xsTxt2 = `民盛保险代理有限公司`;
        ctxc.fillText(xsTxt2, 560, 36);

        /* === 竖版文字设置 === */
        let cbTxt = `本产品由${that.gysFullName}承保`;
        let x = 720,
          y = 170;
        let letterSpacing = 4; // 设置字间距
        for (let i = 0; i < cbTxt.length; i++) {
          const str = cbTxt.slice(i, i + 1).toString();
          ctxc.save();
          ctxc.textBaseline = "top";
          ctxc.fillText(str, x, y);
          ctxc.restore();
          y += ctxc.measureText(str).width + letterSpacing; // 计算文字宽度
        }

        ctxc.textAlign = "center";
        ctxc.font = "bold 38px Arial";

        ctxc.textAlign = "left";
        ctxc.fillStyle = "#FFFFFF";
        ctxc.fillRect(0, 1006, 750, 260);

        let gap = -80;
        ctxc.fillStyle = "#282828";
        ctxc.font = "bold 36px sans-serif";

        ctxc.fillText(that.name, 195, 1140 + gap);
        ctxc.font = "bold 28px sans-serif";
        ctxc.fillText(that.phone, 195, 1180 + gap);

        ctxc.fillStyle = "#282828";
        ctxc.font = "bold 24px sans-serif";
        ctxc.fillText(that.companyName, 25, 1235 + gap);
        ctxc.fillText("执业证号：", 25, 1275 + gap);
        ctxc.fillText(that.certificate, 155, 1275 + gap);

        ctxc.fillStyle = "#957C66";
        ctxc.font = "bold 20px sans-serif";
        if (that.canvasQRCodeUrl) {
          ctxc.fillText("长按二维码了解详情", 558, 1282 + gap);
        }
        var newimgQRCode = new Image();
        newimgQRCode.setAttribute("crossOrigin", "Anonymous");
        let ewmImgUrl =
          that.canvasQRCodeUrl ||
          "//wxou.mschn.cn/app_h5/insurance/img/repalce.png";
        newimgQRCode.src = ewmImgUrl;
        newimgQRCode.onload = function () {
          // 绘制边框
          if (that.canvasQRCodeUrl) {
            that.drawLine(ctxc, 571, 1019, 731, 1019, "#957C66", 1);
            that.drawLine(ctxc, 731, 1019, 731, 1180, "#957C66", 1);
            that.drawLine(ctxc, 731, 1180, 571, 1180, "#957C66", 1);
            that.drawLine(ctxc, 571, 1180, 571, 1019, "#957C66", 1);
            // 绘制二维码
            ctxc.drawImage(newimgQRCode, 576, 1024, 150, 150);
          }
          ctxc.restore();
          /* === 绘制用户圆形头像 === */
          var imgAvatar = new Image();
          imgAvatar.setAttribute("crossOrigin", "Anonymous");
          let avatarUrl =
            that.headImg || "//wxou.mschn.cn/app_h5/insurance/img/man.png";
          imgAvatar.src = avatarUrl;
          imgAvatar.onload = function () {
            let r = 60,
              w = 120,
              h = 120,
              ctx_x = 40,
              ctx_y = 990,
              cx = ctx_x + r, //100
              cy = ctx_y + r; // 1050
            ctxc.beginPath();
            ctxc.arc(cx, cy, r, 0, 2 * Math.PI);
            ctxc.lineWidth = "40";
            ctxc.strokeStyle = "#FFFFFF";
            ctxc.stroke();
            ctxc.clip();
            ctxc.drawImage(imgAvatar, ctx_x, ctx_y, w, h);
            ctxc.restore();
            var dataURL = canvas.toDataURL("image/jpeg", 0.8);
            console.log(dataURL);
            // that.dataURL = dataURL;
            saveFile(dataURL, type);
          };
          // })
          // .catch(() => {});
        };
      };
    },
  },
};
</script>

<style lang="less" scoped>
@import "./common.less";
@import "./style.less";
</style>
